package com.linlong.linlongchat.handler;


import com.alibaba.fastjson.JSON;
import com.linlong.linlongchat.IMService;
import com.linlong.linlongchat.domain.po.Result;
import com.linlong.linlongchat.domain.websocket.data.ChatMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.internal.StringUtil;

public class ChatHandler {
    public static void execute(ChannelHandlerContext ctx, TextWebSocketFrame frame){
        try{
            ChatMessage chat = JSON.parseObject(frame.text(), ChatMessage.class);
                if(StringUtil.isNullOrEmpty(chat.getTarget())){
                    ctx.channel().writeAndFlush(Result.fail("消息发送失败，发送消息前请先指定目标用户"));
                    return;
                }
                Channel channel = IMService.USERS.get(chat.getTarget());
                if(null == channel || !channel.isActive()){
                    ctx.channel().writeAndFlush(Result.fail("消息发送失败，目标用户" + chat.getTarget() + "不在线"));
                    return;
                }else {
                    channel.writeAndFlush(Result.ok("私聊消息（"+chat.getTargetId()+")",chat.getContent()));
                }

        }catch (Exception e){
            ctx.channel().writeAndFlush(Result.fail("发送消息格式错误，请确认后重试"));
        }
    }
}
